package com.five.core.exception;


import com.five.core.result.Result;
import com.five.core.result.ResultEnum;
import com.five.core.utils.JsonUtils;
import com.five.core.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomerExceptionResolver implements HandlerExceptionResolver {

    // 1. 日志对象：使用 SLF4J 门面（推荐，而非直接依赖 Logback 实现）
    private final Logger log = LoggerFactory.getLogger(CustomerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception exception) {
        String msg;
        Integer code;

        // 2. 区分异常类型，调整日志级别（自定义异常用 WARN，未知异常用 ERROR）
        if (exception instanceof CustomerException) {
            // 自定义异常：业务已知异常
            CustomerException customerException = (CustomerException) exception;
            ResultEnum resultEnum = customerException.getResultEnum();
            code = resultEnum.getCode();
            msg = resultEnum.getMessage();
            log.warn("自定义业务异常 | code: {}, message: {}", code, msg, exception);
        } else {
            // 未知异常：系统异常，用 ERROR 级别（需重点关注）
            log.error("系统未知异常 | 异常信息: {}", exception.getMessage(), exception);
            code = ResultEnum.UNKNOWN_EXCEPTION.getCode();
            msg = ResultEnum.UNKNOWN_EXCEPTION.getMessage();
        }

        // 3. 响应 JSON：关闭 PrintWriter 避免资源泄漏，设置响应头确保 JSON 格式正确
        response.setContentType("application/json;charset=UTF-8"); // 关键：指定 JSON 响应类型
        response.setCharacterEncoding("UTF-8"); // 避免中文乱码
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            Result result = Result.buildFail(code, msg);
            printWriter.write(JsonUtils.objectToJson(result));
            printWriter.flush(); // 强制刷新缓冲区，确保响应发送
        } catch (IOException e) {
            // 记录响应失败的日志（避免异常被吞）
            log.error("异常响应 JSON 失败 | 原因: {}", e.getMessage(), e);
        } finally {
            // 关闭流，释放资源（防止内存泄漏）
            if (printWriter != null) {
                printWriter.close();
            }
        }
        ResponseUtils.responseToJson(response, JsonUtils.objectToJson(Result.buildFail(code, msg)));
        // 返回空 ModelAndView：表示已手动处理响应，Spring 不再后续渲染页面
        return new ModelAndView();
    }
}